package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.AppVariable;
import com.example.demo.common.ArticleinfoUtils;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.AnotherArtinfo;
import com.example.demo.entity.Articleinfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.ArticleService;
import org.apache.tomcat.jni.Proc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-08-30
 * Time:15:55
 */
@RestController
@RequestMapping("/art")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    /**
     * 展示文章
     * @param request
     * @return
     */
    @RequestMapping("/mylist")
    public AjaxResult getMyList(HttpServletRequest request) {
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo == null) {
            return AjaxResult.fail(-1, "非法请求");
        }
        // 通过用户 id 查询该用户的文章列表页.
        List<Articleinfo> list = articleService.getMyList(userinfo.getId());
        for (Articleinfo item : list) {
            String content = item.getContent();

            if (content.length() > 100) {
                item.setContent(String.format("%s...",
                        content.substring(1, 100)));
            }
        }

        return AjaxResult.success(list);
    }

    /**
     * 删除文章
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/del")
    public AjaxResult del(Integer id, HttpServletRequest request) {
        if (id == null || id <= 0) {
            //参数有误
            return AjaxResult.fail(-1, "参数异常");
        }
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo == null) {
            return AjaxResult.fail(-1, "用户未登录");
        }
        return AjaxResult.success(articleService.del(id, userinfo.getId()));
    }

    @RequestMapping("/detail")
    public AjaxResult getDetail(Integer id) {
        if (id == 0 || id <= 0) {
            return AjaxResult.fail(-1, "非法参数");
        }
        return AjaxResult.success(articleService.getDetail(id));
    }

    @RequestMapping("/incr-rcount")
    public AjaxResult incrRCount(Integer id) {
        if (id != null && id > 0) {
            return AjaxResult.success(articleService.incrRCount(id));
        }
        return AjaxResult.fail(-1, "非法参数");
    }

    @RequestMapping("/add")
    public AjaxResult add(Articleinfo articleinfo, HttpServletRequest request) {
        // 1.非空校验
        if (articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())
                || !StringUtils.hasLength(articleinfo.getContent())) {
            // 非法参数
            return AjaxResult.fail(-1, "非法参数");
        }
        // 2.数据库添加操作
        // (1)得到 uid
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo == null || userinfo.getId() <= 0) {
            return AjaxResult.fail(-1, "无效的登录用户");
        }
        articleinfo.setUid(userinfo.getId());
        // (2)添加数据库并返回结果
        return AjaxResult.success(articleService.add(articleinfo));
    }

    @RequestMapping("/update")
    public AjaxResult update(Articleinfo articleinfo, HttpServletRequest request) {
        // 1.非空校验
        if (articleinfo == null || !StringUtils.hasLength(articleinfo.getTitle())
                || !StringUtils.hasLength(articleinfo.getContent())
                || articleinfo.getId() == null) {
            // 非法参数
            return AjaxResult.fail(-1, "非法参数");
        }
        // 2.得到档期啊登录用户的id
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo == null && userinfo.getId() == null) {
            // 无效登录用户
            return AjaxResult.fail(-2, "无效登录用户");
        }
        // 核心代码（解决了修改文章归属人判定的问题）
        articleinfo.setUid(userinfo.getId());
        articleinfo.setUpdatetime(LocalDateTime.now());
        return AjaxResult.success(articleService.update(articleinfo));
    }

    /**
     * 查询列表根据分页
     * 分页功能
     *
     * @param pindex 当前的页码（从一开始）
     * @param psize  每页显示的条数
     * @return
     */
    @RequestMapping("/listbypage")
    public AjaxResult getListByPage(Integer pindex, Integer psize) {
        // 1.参数矫正
        if (pindex == null || pindex <= 1) {
            pindex = 1;
        }
        if (psize == null || psize <= 2) {
            psize = 2;
        }
        // 分页公式的值 = (当前页码-1) * 每页显示条数
        int offset = (pindex - 1) * psize;
        // 文章列表数据
        List<Articleinfo> list = articleService.getListByPage(psize, offset);
        // 当前列表总共有多少页
        // 1.查询总共有多少条数据
        int totalCount = articleService.getCount();
        // 2.总条数/psize（每页显示条数）
        double pcountdb = totalCount / (psize * 1.0);
        // 3.使用进一法得到总页数
        int pcount = (int) Math.ceil(pcountdb);
        HashMap<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("pcount", pcount);
        return AjaxResult.success(result);
    }

    /**
     * 草稿
     * @param id
     * @param title
     * @param content
     * @param request
     * @return
     */
    @RequestMapping("/draft")
    public AjaxResult SaveDraft(Integer id, String title, String content,HttpServletRequest request) {
       Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo == null && userinfo.getId() == null) {
            // 无效登录用户
            return AjaxResult.fail(-2, "无效登录用户");
        }
        //这里的是指 修改后的文章存入到草稿箱

        if (id != null){
            //获取文章
            Articleinfo articleinfo = articleService.getByuid(id);
            // 非空校验
            if (articleinfo.getUid() != userinfo.getId()){
                return AjaxResult.fail(-1, "无效登录用户");
            }
            return AjaxResult.success(articleService.updateToDraft(userinfo.getId(), articleinfo.getId(), title, content));
        }
        //添加新文章到草稿箱
        return AjaxResult.success(articleService.SaveDraft(userinfo.getId(),title,content));
    }

    /**
     * 定时发布
     * @param articleinfo
     * @param anotherArtinfo
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping("/timeadd")
    public AjaxResult timePushById(Articleinfo articleinfo, AnotherArtinfo anotherArtinfo,
                                   HttpServletRequest request) throws ParseException {
        // 非空校验
        if (anotherArtinfo == null || !StringUtils.hasLength(anotherArtinfo.getDay()) ||
                !StringUtils.hasLength(anotherArtinfo.getHour()) ||
                !StringUtils.hasLength(anotherArtinfo.getMinute()) ||
                !StringUtils.hasLength(anotherArtinfo.getMonth()) ||
                !StringUtils.hasLength(anotherArtinfo.getYear()) ||
                !StringUtils.hasLength(articleinfo.getContent()) ||
                !StringUtils.hasLength(articleinfo.getTitle())){
            return AjaxResult.fail(-1,"参数错误");
        }
        anotherArtinfo.setSecond("0");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String postTime = anotherArtinfo.getYear() + "-" + anotherArtinfo.getMonth() + "-"
                + anotherArtinfo.getDay() + " " + anotherArtinfo.getHour() + ":"
                + anotherArtinfo.getMinute();
        // 得到用户设定的时间
        Date setTime = dateFormat.parse(postTime);

        //判断用户设定的时间格式是否符合
        String timeStr = dateFormat.format(setTime);
        if (!timeStr.equals(postTime)){
            //输入的时间不正确
            return AjaxResult.fail(-2,"参数错误");
        }

        //判断是否设定为当前时间之前的时间
        //获取当前时间
        Date localTime = new Date();
        if (setTime.getTime() - localTime.getTime() < 0){
            return AjaxResult.fail(-2,"参数错误");
        }

        // 只能设置未来 7 天的定时发布
        if (setTime.getTime() - localTime.getTime() > AppVariable.REGULAR_TIME){
            return AjaxResult.fail(-3,"参数错误");
        }
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo == null || userinfo.getId() <= 0) {
            // 无效的登录用户
            return AjaxResult.fail(-3, "无效的登录用户");
        }
        articleinfo.setUid(userinfo.getId());
        articleinfo.setUpdatetime(LocalDateTime.now());
        // 使用定时器实现定时发布.
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {articleService.add(articleinfo);
                AjaxResult.success(articleService.update(articleinfo));
            }
        }, setTime.getTime() - localTime.getTime());
        return AjaxResult.success(1);
    }

    /**
     * 搜索文章功能
     */
    @RequestMapping("/searchblog")
    public AjaxResult searchBlog(String searchblog,Integer pindex, Integer psize){
        // 1.参数矫正
        if (pindex == null || pindex <= 1) {
            pindex = 1;
        }
        if (psize == null || psize <= 2) {
            psize = 2;
        }
        // 分页公式的值 = (当前页码-1) * 每页显示条数
        int offset = (pindex - 1) * psize;
        // 文章列表数据
        List<Articleinfo> list = articleService.getMyListBySearch(psize, offset,searchblog);
        if (list.size() <= 0){
            return AjaxResult.fail(-1,"未查找到");
        }
        // 当前列表总共有多少页
        // 1.查询总共有多少条数据
        int totalCount = articleService.getCount();
        // 2.总条数/psize（每页显示条数）
        double pcountdb = totalCount / (psize * 1.0);
        // 3.使用进一法得到总页数
        int pcount = (int) Math.ceil(pcountdb);
        HashMap<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("pcount", pcount);
        System.out.println("list = "+list);
        return AjaxResult.success(result);
    }

}